<template>
  <div class="complaint-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索投诉编号/投诉人/餐厅"
        style="width: 300px"
        clearable
      >
        <template #prefix>
          <span style="margin-right: 8px">🔍</span>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <span style="margin-right: 5px">+</span>新建投诉
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="filteredComplaints" border style="width: 100%">
      <el-table-column prop="complaintId" label="投诉编号" width="180" sortable />
      <el-table-column prop="customer" label="投诉人" width="120" />
      <el-table-column prop="restaurant" label="餐厅名称" width="150">
        <template #default="{ row }">
          <el-tag type="info">{{ row.restaurant }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="submitDate" label="提交时间" width="150">
        <template #default="{ row }">
          {{ formatDate(row.submitDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="content" label="投诉内容" width="200">
        <template #default="{ row }">
          <span v-if="row.content.length > 20">{{ row.content.slice(0, 20) }}...</span>
          <span v-else>{{ row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="处理状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusType[row.status]">
            {{ statusOptions.find(s => s.value === row.status)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑投诉记录' : '新建投诉'"
      width="600"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="投诉编号" prop="complaintId">
          <el-input v-model="formData.complaintId" :disabled="isEditMode" />
        </el-form-item>
        <el-form-item label="投诉人" prop="customer">
          <el-input v-model="formData.customer" />
        </el-form-item>
        <el-form-item label="餐厅名称" prop="restaurant">
          <el-select v-model="formData.restaurant" placeholder="请选择餐厅">
            <el-option
              v-for="item in restaurants"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间" prop="submitDate">
          <el-date-picker
            v-model="formData.submitDate"
            type="datetime"
            placeholder="选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="投诉内容" prop="content">
          <el-input type="textarea" v-model="formData.content" rows="3" />
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'


// SessionStorage 操作工具
const STORAGE_KEY = 'complaint_management_state'
const saveToStorage = (state) => {
  sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state))
}
const loadFromStorage = () => {
  const data = sessionStorage.getItem(STORAGE_KEY)
  return data ? JSON.parse(data) : {}
}

// 日期格式化（包含时间）
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 餐厅列表（参考网页8的商家数据）
const restaurants = [
  '海底捞火锅',
  '星巴克咖啡',
  '肯德基快餐',
  '绿茶餐厅',
  '西贝莜面村',
  '必胜客披萨'
]

// 处理状态选项（根据网页8的状态规范）
const statusOptions = [
  { value: 0, label: '待处理' },
  { value: 1, label: '处理中' },
  { value: 2, label: '已解决' }
]
const statusType = { 0: 'danger', 1: 'warning', 2: 'success' }

// 从 SessionStorage 加载初始状态
const storedState = loadFromStorage()

// 10条投诉测试数据（基于网页8的投诉场景，优先从 SessionStorage 恢复）
const complaints = ref(storedState.complaints || [
  {
    id: 1,
    complaintId: 'CT202405001',
    customer: '张女士',
    restaurant: '海底捞火锅',
    submitDate: '2024-05-15 14:30:00',
    content: '服务员态度恶劣，用餐期间多次呼叫无回应',
    status: 0
  },
  {
    id: 2,
    complaintId: 'CT202405002',
    customer: '李先生',
    restaurant: '星巴克咖啡',
    submitDate: '2024-05-16 10:15:00',
    content: '购买的拿铁咖啡中发现异物，要求退款赔偿',
    status: 1
  },
  {
    id: 3,
    complaintId: 'CT202405003',
    customer: '王先生',
    restaurant: '肯德基快餐',
    submitDate: '2024-05-17 15:45:00',
    content: '外卖订单缺失汉堡套餐中的薯条和饮料',
    status: 2
  },
  {
    id: 4,
    complaintId: 'CT202405004',
    customer: '赵小姐',
    restaurant: '绿茶餐厅',
    submitDate: '2024-05-18 09:30:00',
    content: '预定的包厢被无故取消，且未提前通知',
    status: 0
  },
  {
    id: 5,
    complaintId: 'CT202405005',
    customer: '陈同学',
    restaurant: '西贝莜面村',
    submitDate: '2024-05-19 16:20:00',
    content: '菜品中发现头发，要求重新制作并赔偿',
    status: 1
  },
  {
    id: 6,
    complaintId: 'CT202405006',
    customer: '周女士',
    restaurant: '必胜客披萨',
    submitDate: '2024-05-20 11:00:00',
    content: '披萨饼底烤焦，配料与菜单描述不符',
    status: 2
  },
  {
    id: 7,
    complaintId: 'CT202405007',
    customer: '吴先生',
    restaurant: '海底捞火锅',
    submitDate: '2024-05-21 17:10:00',
    content: '等位超过2小时未安排入座，服务混乱',
    status: 0
  },
  {
    id: 8,
    complaintId: 'CT202405008',
    customer: '郑女士',
    restaurant: '星巴克咖啡',
    submitDate: '2024-05-22 08:45:00',
    content: '会员积分兑换被无故取消，要求恢复',
    status: 1
  },
  {
    id: 9,
    complaintId: 'CT202405009',
    customer: '孙先生',
    restaurant: '肯德基快餐',
    submitDate: '2024-05-23 13:30:00',
    content: '早餐套餐配送超时1小时，食物已凉',
    status: 2
  },
  {
    id: 10,
    complaintId: 'CT202405010',
    customer: '林女士',
    restaurant: '绿茶餐厅',
    submitDate: '2024-05-24 14:00:00',
    content: '菜品价格与菜单标价不符，存在欺诈行为',
    status: 0
  }
])

// 搜索功能（支持多字段模糊搜索，从 SessionStorage 恢复搜索词）
const searchText = ref(storedState.searchText || '')
const filteredComplaints = computed(() => {
  const searchKey = searchText.value.toLowerCase()
  return complaints.value.filter(complaint => {
    return [
      complaint.complaintId,
      complaint.customer,
      complaint.restaurant,
      complaint.content
    ].join('').toLowerCase().includes(searchKey)
  })
})

// 对话框状态管理（从 SessionStorage 恢复）
const dialogVisible = ref(storedState.dialogVisible || false)
const isEditMode = ref(storedState.isEditMode || false)
const formRef = ref(null)
const formData = reactive(storedState.formData || {
  id: null,
  complaintId: '',
  customer: '',
  restaurant: '',
  submitDate: new Date().toISOString().split('.')[0],
  content: '',
  status: 0
})

// 表单验证规则（根据网页8的规范增强）
const formRules = {
  customer: [
    { required: true, message: '请输入投诉人姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度2-10个字符' }
  ],
  restaurant: [{ required: true, message: '请选择餐厅名称', trigger: 'change' }],
  submitDate: [{ required: true, message: '请选择提交时间', trigger: 'change' }],
  content: [
    { required: true, message: '请填写投诉内容', trigger: 'blur' },
    { min: 20, max: 200, message: '内容长度20-200个字符' }
  ],
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }]
}

// 监听关键状态变化，自动保存到 SessionStorage
watch([complaints, searchText, dialogVisible, isEditMode, () => ({ ...formData })], () => {
  saveToStorage({
    complaints: complaints.value,
    searchText: searchText.value,
    dialogVisible: dialogVisible.value,
    isEditMode: isEditMode.value,
    formData: { ...formData }
  })
}, { deep: true })

// 操作函数（根据网页3的流程优化）
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该投诉记录？删除后将不可恢复！', '警告', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消操作',
    type: 'warning'
  }).then(() => {
    complaints.value = complaints.value.filter(c => c.id !== id)
    ElMessage.success('投诉记录已删除')
  })
}

const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = complaints.value.findIndex(c => c.id === formData.id)
    complaints.value.splice(index, 1, { ...formData })
  } else {
    complaints.value.push({
      ...formData,
      id: Date.now(),
      submitDate: formData.submitDate || new Date().toISOString().split('.')[0]
    })
  }
  dialogVisible.value = false
}


const resetForm = () => {
  formData.id = null
  formData.complaintId = ''
  formData.customer = ''
  formData.restaurant = ''
  formData.submitDate = new Date().toISOString().split('.')[0]
  formData.content = ''
  formData.status = 0
}

// 初始化时确保状态正确恢复
onMounted(() => {
  // 如果从存储中恢复了对话框状态，确保表单验证规则已正确应用
  if (dialogVisible.value && formRef.value) {
    formRef.value.clearValidate()
  }
})


</script>

<style scoped>
.complaint-management {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  font-weight: 500;
}

.el-textarea__inner {
  height: 80px;
}
</style>

<style>
.star {
  position: absolute;
  user-select: none;
  pointer-events: none;
  z-index: 1000;
}

.floating-star {
  animation: floatAndFade 2s ease-in-out forwards;
}

@keyframes floatAndFade {
  0% {
    transform: translateY(0px) scale(1);
    opacity: 1;
  }
  70% {
    transform: translateY(-150px) scale(1.1);
    opacity: 0.7;
  }
  100% {
    transform: translateY(-200px) scale(1.2);
    opacity: 0;
  }
}
</style>